package com.mjfeed.adapter;

import java.math.BigDecimal;
import java.util.List;

import com.mjfeed.activity.MainActivity;
import com.mjfeed.activity.R;
import com.mjfeed.bean.CartItemJSON;
import com.mjfeed.bean.ProductJSON;
import com.mjfeed.service.CartItemService;
import com.mjfeed.service.ProductService;
import com.mjfeed.util.NetUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 购物车
 * @author zhaominglei
 * @date 2014-12-21
 * 
 */
public class CartItemAdapter extends BaseAdapter {
	private ProductService productService = new ProductService();
	private CartItemService cartItemService = new CartItemService();
	
	private List<CartItemJSON> cartItems;
	private Context context;
	private MainActivity mainActivity;
	@SuppressWarnings("unused")
	private ProgressBar progressBar;
	private ImageLoader imageLoader = null;
	private DisplayImageOptions options = null;
	private CartItemJSON cartItemJSON;
	private String referer; //来自那个链接
	
	public CartItemAdapter(Context context, List<CartItemJSON> cartItems) {
		super();
		this.context = context;
		mainActivity = (MainActivity)context;
		this.cartItems = cartItems;
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(context));

		options = new DisplayImageOptions.Builder()
				.displayer(new RoundedBitmapDisplayer(0xff000000, 10))
				.cacheInMemory().cacheOnDisc().build();
	}

	public List<CartItemJSON> getCartItems() {
		return cartItems;
	}


	public void setCartItems(List<CartItemJSON> cartItems) {
		this.cartItems = cartItems;
	}

	@Override
	public int getCount() {
		return cartItems.size();
	}

	@Override
	public Object getItem(int position) {
		return cartItems.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		RelativeLayout relativeLayout;
		if (convertView != null) {
			relativeLayout = (RelativeLayout) convertView;
		} else {
			relativeLayout = (RelativeLayout) View.inflate(context,
					R.layout.cartitem_item, null);
		}
		progressBar = (ProgressBar) relativeLayout.findViewById(R.id.cart_item_progress);
		ImageView imageView = (ImageView) relativeLayout.findViewById(R.id.cart_item_image);
		ImageView decreaseView = (ImageView) relativeLayout.findViewById(R.id.cart_item_decrease);
		ImageView increaseView = (ImageView) relativeLayout.findViewById(R.id.cart_item_increase);
		ImageView deleteView = (ImageView) relativeLayout.findViewById(R.id.cart_item_delete);
		
		final Long cartItemId = cartItems.get(position).getCartItemId();
		final Long productId = cartItems.get(position).getProductId();
		ProductJSON productJSON = productService.getProductDetail(context, productId);
		Integer quantity = cartItems.get(position).getQuantity();
		BigDecimal price = productJSON.getPrice();
		double subTotal = quantity*price.doubleValue();
		
		imageLoader.displayImage(productJSON.getImageUrl(),	imageView, options);
		((TextView)relativeLayout.findViewById(R.id.cart_item_template_name))
				.setText(productJSON.getName());
		((EditText) relativeLayout.findViewById(R.id.cart_item_template_quantity))
				.setText(String.valueOf(quantity));
		((TextView)relativeLayout.findViewById(R.id.cart_item_template_price))
				.setText(String.valueOf(productJSON.getPrice()));
		((TextView)relativeLayout.findViewById(R.id.cart_item_template_subtotal))
				.setText(String.valueOf(subTotal));
		
		decreaseView.setTag(cartItemId);
		increaseView.setTag(cartItemId);
		deleteView.setTag(cartItemId);
		decreaseView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Long desCartItemId = (Long)v.getTag();
				if (desCartItemId.equals(cartItemId)) {
					updateNum(context, v, "decrease", cartItemId, productId);
				}
			}
		});
		increaseView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Long desCartItemId = (Long)v.getTag();
				if (desCartItemId.equals(cartItemId)) {
					updateNum(context, v, "increase", cartItemId, productId);
				}
			}	
		});
		deleteView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Long desCartItemId = (Long)v.getTag();
				if (desCartItemId.equals(cartItemId)) {
					deleteCartItem(context, v, cartItemId, productId);
				}
			}	
		});
		
		return relativeLayout;
	}

	public void deleteCartItem(Context context, View v, Long cartItemId, Long productId) {
		if (cartItemId == null || productId == null) {
			return;
		}
		cartItemJSON = cartItemService.getById(context, cartItemId);
		if (NetUtils.isConnected(mainActivity)) {
			new CartItemDeleteAsyncTask().execute("");
		} else {
			Toast.makeText(mainActivity, R.string.net_error, Toast.LENGTH_SHORT).show();
			return;
		}
	}

	public void updateNum(Context context, View v, String action, Long cartItemId, Long productId) {
		if (action == null || cartItemId == null || productId == null) {
			return;
		}
		cartItemJSON = cartItemService.getById(context, cartItemId);
		Integer quantity = cartItemJSON.getQuantity();
		if (action.equals("decrease")) {
			if (quantity.intValue() == 1) {
				Toast.makeText(context, R.string.cart_item_check_error1, Toast.LENGTH_SHORT).show();
				return;
			} 
			quantity--;
		}
		if (action.equals("increase")) {
			quantity++;
			if (quantity.intValue() > cartItemJSON.getStock().intValue()) {
				Toast.makeText(context, R.string.cart_item_check_error2, Toast.LENGTH_SHORT).show();
				return;
			}
		} 
		cartItemJSON.setQuantity(quantity);
		
		if (NetUtils.isConnected(mainActivity)) {
			new CartItemUpdateAsyncTask().execute("");
		} else {
			Toast.makeText(mainActivity, R.string.net_error, Toast.LENGTH_SHORT).show();
			return;
		}
		
	}
	
	public class CartItemUpdateAsyncTask extends AsyncTask<String, String, Boolean> {
		@Override
		protected Boolean doInBackground(String... params) {
			return cartItemService.updateCartItem(context, referer, cartItemJSON);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				cartItemService.update(context, cartItemJSON);
				Intent intent = new Intent(mainActivity, MainActivity.class);
				intent.putExtra("referer", "ShoppingFragment");
				mainActivity.startActivity(intent);
				mainActivity.finish();
			} else {
				Toast.makeText(mainActivity, R.string.update_error, Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public class CartItemDeleteAsyncTask extends AsyncTask<String, String, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			return cartItemService.deleteCartItem(context, referer, cartItemJSON);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				cartItemService.delete(context, cartItemJSON);
				Intent intent = new Intent(mainActivity, MainActivity.class);
				intent.putExtra("referer", "ShoppingFragment");
				mainActivity.startActivity(intent);
				mainActivity.finish();
			} else {
				Toast.makeText(mainActivity, R.string.update_error, Toast.LENGTH_SHORT).show();
			}
		}
	}
}
